<?php

class CondominioController extends AdminController implements ItemMenu {

	/* (non-PHPdoc)
	 * @see ItemMenu::cadastrar()
	 */
	public function cadastrar() {
		
		if( isset($_POST) && count($_POST) > 0 ){ 
			
			$this->salvar();
		
		}else{
		
			$view = new View("condominio/gerenciar");
		
			$view->set("condominio.ativo1", "checked");
			
			$view->set("condominio.nome", "");
			$view->set("condominio.telefone", "");
			$view->set("condominio.cnpj", "");
			$view->set("endereco.logradouro", "");
			$view->set("endereco.numero", "");
			$view->set("endereco.complemento", "");
			$view->set("endereco.bairro", "");
			$view->set("endereco.cep", "");
			$view->set("endereco.cidade", "");
			$view->set("endereco.estados.select", $this->montaSelectEstado("RN"));
			
			$view->set("condominio.id", "");
			$view->set("endereco.id", "");
			
			$view->set("form.action", $this->getAction() );
			$view->set("form.title.action", ucfirst( $this->getAction() ));
			
			$this->template->content = $view;
			
		}
		
	}

	/* (non-PHPdoc)
	 * @see ItemMenu::editar()
	 */
	public function editar() {
		
		if( isset($_POST) && count($_POST) > 0 ){ 
			
			$this->salvar();
		
		}else{
		
			$idParam = $this->getIdFrom("condominio_id"); //($this->isAdministrador()) ? $this->getParam("id") : $this->auth->getUserData("condominio_id") ;
			
			if( $this->testIsValidId($idParam) ){
				
				$condominioModel = new CondominioModel();
				$enderecoModel = new EnderecoModel();
				$condominio = $condominioModel->findById( $idParam );
				
				if( count( $condominio ) > 0 ){
				
					$endereco = $enderecoModel->findById( $condominio["endereco_id"] );
					
					if( count( $endereco ) > 0 ){
					
						$view = new View("condominio/gerenciar");
						
						$view->set("condominio.ativo".$condominio["ativo"], "checked");
						
						$view->set("condominio.nome", $condominio["nome"]);
						$view->set("condominio.telefone", $condominio["telefone"]);
						$view->set("condominio.cnpj", $condominio["cnpj"]);
						$view->set("endereco.logradouro", $endereco["logradouro"]);
						$view->set("endereco.numero", $endereco["numero"]);
						$view->set("endereco.complemento", $endereco["complemento"]);
						$view->set("endereco.bairro", $endereco["bairro"]);
						$view->set("endereco.cep", $endereco["cep"]);
						$view->set("endereco.cidade", $endereco["cidade"]);
						$view->set("endereco.estados.select", $this->montaSelectEstado( $endereco["estado"] ));
				
						$view->set("condominio.id", Encryption::encode($condominio["id"]) );
						$view->set("endereco.id", Encryption::encode($endereco["id"]) );
						
						$view->set("form.action", $this->getAction() );
						$view->set("form.title.action", ucfirst( $this->getAction() ));
						
						$this->template->content = $view;
						
					}
				
				}
			
			}else{
				
				$this->redirecionaAcessoIdInvalido("Condomínio", "condominio");
							
			}
			
		}
		
	}

	/* (non-PHPdoc)
	 * @see ItemMenu::listar()
	 */
	public function listar() {
		
		$view = new View("_components/jquery_table");
		
		$view->set("table.title", "Todos os Condomínios");
		$view->set("table.black.icon16", "list");
		$view->set("table.new.label", "Novo Condomínio");
		$view->set("table.new.url", "condominio/cadastrar");
		
		$view->set("table.head", 
			ViewList::merge( "th",
				CondominioModel::createHeadersToTable()
			) 
		);
		
		$view->set("table.body", 
			ViewList::merge( "condominio/tr", 
				CondominioModel::listAllToTable()
			) 
		);
		
		$this->template->content = $view;
		
	}

	/* (non-PHPdoc)
	 * @see ItemMenu::apagar()
	 */
	public function apagar() {
	
		$idParam = $this->getIdFrom("condominio_id"); //($this->isAdministrador()) ? $this->getParam("id") : $this->auth->getUserData("condominio_id") ;
				
		if( $this->testIsValidId($idParam) ){
		
			$condominioModel = new CondominioModel();
			$condominio = $condominioModel->delete($idParam);
			
			$this->addGrowlMsgs( Messages::get("apagadoComSucesso", array( "{objeto}" => $condominio['nome'] )) );
			$this->redirect->goToAction("index");
			
		}else{
			
			$this->redirecionaAcessoIdInvalido("Condomínio", "condominio");
						
		}
		
	}

	/* (non-PHPdoc)
	 * @see ItemMenu::ver()
	 */
	public function ver() {
				
		$idParam = $this->getIdFrom("condominio_id"); //($this->isAdministrador()) ? $this->getParam("id") : $this->auth->getUserData("condominio_id") ;
		
		if( $this->testIsValidId($idParam) ){	
		
			$view = new View("condominio/ver");
			
			$condominioModel = new CondominioModel();
			$condominio = $condominioModel->findById($idParam);
			
			$this->processViewConfigurarVer(&$view, $condominio, false);
			
			$this->template->content = $view;
			
		}else{
			
			$this->redirecionaAcessoIdInvalido("Condomínio", "condominio");
						
		}
		
	}
	
	public function configurar() {
		
		if( isset($_POST) && count($_POST) > 0 ){ 
			
			$this->salvar();
		
		}else{
		
			$idParam = $this->getIdFrom("condominio_id"); //($this->isAdministrador()) ? $this->getParam("id") : $this->auth->getUserData("condominio_id") ;
		
			if( $this->testIsValidId($idParam) ){	
			
				$view = new View("condominio/ver");
				
				$condominioModel = new CondominioModel();
				$condominio = $condominioModel->findById($idParam);
				
				$this->processViewConfigurarVer(&$view, $condominio);
				
				$this->template->content = $view;
				
			}else{
				
				$this->redirecionaAcessoIdInvalido("Condomínio", "condominio");
							
			}
			
		}
		
	}

	// Private Methods ============================================================================
	
	private function processViewConfigurarVer(View $view, $condominio, $isConfigurar=true) {
		
		$view->set( "condominio.id", $isConfigurar ? Encryption::encode($condominio["id"]) : "" );
		$view->set( "condominio.nome", $condominio["nome"] );
		$view->set( "condominio.telefone", Mask::maskNumber( $condominio["telefone"], Mask::$TELEFONE ) );
		$view->set( "condominio.cnpj", Mask::maskNumber( $condominio["cnpj"], Mask::$CNPJ ) );
		$view->set( "condominio.endereco", EnderecoModel::fullAddress( $condominio["endereco_id"] ) );
		
		$content_line_sindico = "";
		$content_line_subsindico = "";

		$campos = array(
			"sindico" => "Síndico", 
			"subsindico" => "Subsíndico" 
		);
		
		if( $isConfigurar ){
			
			$selectClientes = ClienteModel::listAllToSelect($condominio["id"]);
			foreach ( $campos as $label => $rotulo ){
				$selectArray = ClienteModel::markInSelectArray( $condominio[ $label."_id" ], $selectClientes ); 
				${"content_line_".$label} = $this->montaSelectClientes( $rotulo, "condominio_".$label."_id", $selectArray );
			}
			
		}else {
			$naoInformado = Messages::get("naoInformado");
			foreach ( $campos as $label => $rotulo ){
				if( $condominio[ $label."_id" ] == 0 ){
					${"content_line_".$label} = $this->preparaInputTextDisabledCliente( $rotulo, $naoInformado );
				}else{
					$clienteModel = new ClienteModel();
					$cliente = $clienteModel->findById( $condominio[ $label."_id" ] );
					${"content_line_".$label} = $this->preparaInputTextDisabledCliente( $rotulo, $cliente["nome"] );
				}
			}
		}
		
		$view->set( "gerenciar", $isConfigurar ? "Gerenciar" : "Ver" );

		$view->set( "form.action", $isConfigurar ? "condominio/configurar" : "#" );
		$view->set( "form.image", $isConfigurar ? "cog" : "eye" );
		$view->set( "form.buttons.display", $isConfigurar ? "block" : "none" );
		$view->set( "form.condominio.sindico", $content_line_sindico );
		$view->set( "form.condominio.subsindico", $content_line_subsindico );
		$view->set( "form.cancelar.controller", $this->getController() );
		
	}
	
	private function montaSelectEstado($selecionado) {
		
		return HtmlComponent::select("Estado", "small", "endereco_estado", Estados::convertToSelectArray( $selecionado ));
		
	}

	private function montaSelectClientes($label ,$name, $selectArray) {
		
		return HtmlComponent::select($label, "large", $name, $selectArray);
		
	}
	
	private function preparaInputTextDisabledCliente($rotulo, $nome) {
		
		return HtmlComponent::inputText($rotulo, "large", "", $nome, true);
		
	}

	public function salvar() {
		
//		if( isset($_POST) && count($_POST) > 0 ){

			$endereco = array();
			$condominio = array();
			$enderecoModel = new EnderecoModel();
			$condominioModel = new CondominioModel();
			
			foreach ( $_POST as $key => $value ){
				$camp = explode("_", $key);
				$type = array_shift( $camp );
				$camp = implode("_", $camp);
				if( $camp == "id" ){
					if( $value != "" )
						${$type}["id"] = Encryption::decode($value);
				}else{
					if( in_array( $camp, array( "cep", "telefone", "cpf", "cnpj" ) ) )
						${$type}[$camp] = Mask::unMaskNumber($value);
					else
						${$type}[$camp] = $value;
				}
			}
			
			if( count($endereco) > 0 ){
				if( array_key_exists("id", $endereco) ){
					if( $this->testIsValidId( $endereco["id"] ) ){
						$endereco = $enderecoModel->merge($endereco);
					}else{
						$this->addGrowlMsgs( Messages::get("idInvalido", array( "{objeto}" => "Endereço" )) );
						$this->redirect->goToUrl("condominio");
						exit();
					}
				}else{ 
					$endereco = $enderecoModel->persist($endereco);
				}
				$condominio[ "endereco_id" ] = $endereco[ "id" ];
			}
			
			$isNovoModel = false;
			
			if( count($condominio) > 0 ){
				if( array_key_exists("id", $condominio) ){
					if( $this->testIsValidId( $condominio["id"] ) ){
						$isNovoModel = false;
						$condominio = $condominioModel->merge($condominio);
					}else{
						$this->addGrowlMsgs( Messages::get("idInvalido", array( "{objeto}" => "Condomínio" )) );
						$this->redirect->goToUrl("condominio");
						exit();
					}
				}else{ 
					$condominio = $condominioModel->persist($condominio);
					$isNovoModel = true;
				}
			}
			
			// Define a mensagem do aviso
			$msgKey = $isNovoModel ? "salvoComSucesso" : "alteradoComSucesso";
			$this->addGrowlMsgs( Messages::get( $msgKey, array( "{objeto}" => "'".$condominio['nome']."' (Condomínio)")) );
			// Redireciona para index do controller 
			$this->redirect->goToUrl("condominio");
			exit();
			
//		// Em caso de uso indevido, define aviso e redireciona para para a index do controller
//		}else{
//			$this->addGrowlMsgs( Messages::get("requisicaoInvalida") );
//			$this->redirect->goToUrl("condominio");
//			exit();
//		}

	}
	
}

?>